package com.jfee.dds.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.springframework.stereotype.Component;

import java.io.*;

@Slf4j
@Component
public class ProcessDataUtils {

    private String readFileContent(String dbName) {
        BufferedReader br = null;
        String line = null;
        StringBuilder bufAll = new StringBuilder(); //保存修改过后的所有内容，不断增加
        try {
            String filePath = Resources.getResourceURL("init-db.sql").getPath();
            br = new BufferedReader(new FileReader(filePath));
            while ((line = br.readLine()) != null) {
                StringBuilder buf = new StringBuilder();
                buf.append(line);
                //修改内容核心代码
                if (line.startsWith("@USE@")) {
                    buf.replace(0, line.length(), "USE " + dbName + ";");
                }
                bufAll.append(buf);
                bufAll.append("\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                }
            }
        }
        return bufAll.toString();
    }

    //写回文件
    public void writeFile(String dbName) {
        BufferedWriter bw = null;

        try {
            String filePath = Resources.getResourceURL("init-db-run.sql").getPath();
            String content = readFileContent(dbName);
            bw = new BufferedWriter(new FileWriter(filePath));
            bw.write(content);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    bw = null;
                }
            }
        }
    }
}
